//TODO: refactor message building! now string, should be object...
//TODO: refactor message storing
//TODO: could make it like an interface for any messenger

//TODO: could show "typing status"
//TODO: history?
//TODO: to stay online {"ack":14,"ssid":"E38XhUA3GsTHpHZU","messages":[{"to":{"system":"session"},"from":{"system":"client","ssid":"E38XhUA3GsTHpHZU"},"data":{"data":{"ssid":"E38XhUA3GsTHpHZU"},"method":"observed_user_activity"},"seq":17}]}

var uid = "kukufi1";
var pwd = 'Pokus1';
var celebriotalkerchats = [];

var talker = {
    ssid: "",
    ack : 0,
    seq : 0,
    
    contacts : function (list) {
        $("#celebrioloading").remove();
        for (var i = 0; i < list.length; i++ ) {
            var contact = list[i];
            if ($("#skype-"+contact.buid).length) {
                if (contact.primitive == "offline") {
                    $("#skype-"+contact.buid).find(".online").removeClass("online").addClass("offline");
                } else {
                    $("#skype-"+contact.buid).find(".offline").removeClass("offline").addClass("online");
                }
            } else {
                $("<li><div id='skype-"+contact.buid+"' onclick='createMessage(\""+contact.buid+"\");'><span class='"+( contact.primitive != "offline" ? "online": "offline")+"'>X</span>"+contact.alias+" <span class='celebriononemessages'>O</span></div></li>").appendTo("#celebriocontacts");
            }
        }
    },
    
    conversation: function (message) {
        if (!message.msg) {
            return false;
        }
        
        time = talker.getTime(message.timestamp*1000);
       
        if ($("#"+message.buid+"-messages").length>0) {
            if(!celebriotalkerchats[message.buid]) {
                celebriotalkerchats[message.buid] = [];
            }
            celebriotalkerchats[message.buid].push(message);
            var msg = time+" "+ (message.alias ? message.alias : "Me") +": "+message.msg;
            $("<div>"+msg+"</div>").appendTo($("#"+message.buid+"-messages"));
            return true;
        } else {
            talker.notOpened(message);
            return false;
        }
    },
    
    notOpened : function (message) {
        if(!celebriotalkerchats[message.buid]) {
            celebriotalkerchats[message.buid] = [];
        }
        time = talker.getTime(message.timestamp*1000);
        celebriotalkerchats[message.buid].push(message);
        $("#skype-"+message.buid).find(".celebriononemessages").removeClass("celebriononemessages").addClass("celebrionewmessages");
    },
    
    markRead : function (message) {
        if (!message) return;
        data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"uid":"'+uid+'","proto":"prpl-skype","buid":"'+message.buid+'","last_index":'+message.index+',"ssid":"'+talker.ssid+'"},"method":"mark_msgs_as_read"},"seq":'+(talker.seq++)+'}]}';
        $.post(link, {
            "data" : data
        });
        $("#skype-"+message.buid).find(".celebrionewmessages").removeClass("celebrionewmessages").addClass("celebriononemessages");
    },
    
    unread : function (msgs) {
        for (var author in msgs) {
            var messages = msgs[author].msgs;
            for (var msg in messages) {
                talker.notOpened(messages[msg]);
            }
        }
    },
    
    getTime : function (time) {
        date = new Date();
        if (time) {
            date.setTime(time);
        }
        return date.getHours() + ":" + (date.getMinutes() < 10 ? "0" : "") + date.getMinutes();
    },
    
    getSsid : function () {
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        var string_length = 16;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }
        var data = '{"ack":'+talker.ack+',"ssid":"'+randomstring+'","messages":[{"seq":0,"from":{"system":"client","ssid":"'+randomstring+'"},"to":{"system":"ssid"},"data":{"method":"get_ssid","data":{"ssid":"'+randomstring+'"}}}]}';
        $.post(link, {
            method: "rest_rpc", 
            "data" : data
        },
        function(retdata) {
            talker.ssid = retdata.message.data.messages[0].message.data.edata.ssid;
            talker.process(retdata);
            talker.reui();
        });
    },
    
    reui : function () {
        //TODO: version?
        data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"session"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"version":"2011.8.24","ssid":"'+talker.ssid+'"},"method":"reui_session"},"seq":'+(talker.seq++)+'}]}';
        $.post(link, {
            "data" : data
        },
        function(retdata) {
            talker.process(retdata);
            talker.log_event();            
        });
    },
                                
    log_event : function () {
        //TODO: log correctly?
        d = new Date();
        data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"monitor"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"uid":null,"proto":null,"events":[{"namespace":"reui.page_load","data":{"load_time":3131,"page_loads":1,"referrer":"","winlocation":"https://imo.im/","doclocation":"https://imo.im/","version":1314222361.8,"ssid":"'+talker.ssid+'","size":[1280,800],"ua":"Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0"},"start_time":'+d.getTime()/1000+',"end_time":'+d.getTime()/1000+'}],"ssid":"'+talker.ssid+'"},"method":"log_event"},"seq":'+(talker.seq++)+'}]}';
        $.post(link, {
            "data" : data
        },
        function(retdata) {
            startPolling();
            talker.process(retdata);
            talker.accountLogin(uid,pwd);
            
        });  
    },
                                
    accountLogin : function (nick, pass) {
        data =  '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"passwd":"'+pass+'","captcha":null,"edata":{"steamauthtoken":""},"uid":"'+nick+'","proto":"prpl-skype","ssid":"VI2xwZHB5lKLkgpH"},"method":"account_login"},"seq":'+(talker.seq++)+'}]}';
        //data = 	'{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"passwd":"'+pass+'","captcha":null,"uid":"'+nick+'","proto":"prpl-skype","ssid":"'+talker.ssid+'"},"method":"account_login"},"seq":'+(talker.seq++)+'}]}';
        $.post(link, {
            "data" : data
        },
        function(retdata) {
            talker.process(retdata);
            talker.log_login();
        });
    },

    log_login : function () {
        //TODO: log correctly?
        '{"ack":0,"ssid":"VI2xwZHB5lKLkgpH","messages":[{"to":{"system":"monitor"},"from":{"system":"client","ssid":"VI2xwZHB5lKLkgpH"},"data":{"data":{"uid":null,"proto":null,"events":[{"namespace":"reui.remembmer_me","data":{"checked":false,"uid":"kukufi1","proto":"prpl-skype"},"start_time":1314256116.127,"end_time":1314256116.127}],"ssid":"VI2xwZHB5lKLkgpH"},"method":"log_event"},"seq":3}]}';
        data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"monitor"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"uid":null,"proto":null,"events":[{"namespace":"reui.remembmer_me","data":{"checked":false,"uid":"'+uid+'","proto":"prpl-skype"},"start_time":1314256116.127,"end_time":1314256116.127}],"ssid":"'+talker.ssid+'"},"method":"log_event"},"seq":'+(talker.seq++)+'}]}';
        $.post(link, {
            "data" : data
        },
        function(retdata) {
            talker.process(retdata);
            talker.get_promos();
        });  
    },

    get_promos : function () {
        data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"promo"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"edata":{"kind":"web","quantity":1},"ssid":"'+talker.ssid+'"},"method":"get_promos"},"seq":'+(talker.seq++)+'}]}';
        $.post(link, {
            "data" : data
        },
        function(retdata) {
            talker.process(retdata);
            talker.get_alpha();
        });
    },

    get_alpha : function () {
        //        data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"alpha"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"uid":"'+uid+'","proto":"prpl-skype","ssid":"'+talker.ssid+'"},"method":"get_alpha_for_user"},"seq":'+(talker.seq++)+'}]}';
        //        $.post(link, {
        //            "data" : data
        //        },
        //        function(retdata) {
        //            talker.process(retdata);
        talker.observed();
    //        });
    },

    observed : function () {
        data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"session"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"ssid":"'+talker.ssid+'"},"method":"observed_user_activity"},"seq":'+(talker.seq++)+'}]}';
        $.post(link, {
            "data" : data
        },
        function(retdata) {
            talker.process(retdata);
            talker.get_unread();
        });  
    },

    get_unread : function () {
        data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"uid":"'+uid+'","proto":"prpl-skype","ssid":"'+talker.ssid+'"},"method":"get_unread_msgs"},"seq":'+(talker.seq++)+'}]}';
        $.post(link, {
            "data" : data
        },
        function(retdata) {
            talker.process(retdata);
        });
    },
    
    confirmAdd : function (message) {
        $("<div class='confirmadd' title='Add a friend?'>\n\
           User <strong>"+message.buid+"</strong> wants to add you!\n\
           Message: "+message.msg+"\n\
        </div>").dialog({
            buttons: {
                "Accept": function() {
                    $( this ).dialog( "close" );
                    talker.acceptAdd(message.buid);
                },
                "Reject": function() {
                    $( this ).dialog( "close" );
                    talker.denyAdd(message.buid);
                }
            }
        });
},

acceptAdd : function(name) {
    data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"buid":"'+name+'","group":"Skype","alias":"","uid":"'+uid+'","proto":"prpl-skype","ssid":"'+talker.ssid+'"},"method":"auth_add"},"seq":'+(talker.seq++)+'}]}';
    $.post(link, {
        "data" : data
    });
},

denyAdd : function(name) {
    data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"buid":"'+name+'","uid":"'+uid+'","proto":"prpl-skype","ssid":"'+talker.ssid+'"},"method":"auth_deny"},"seq":'+(talker.seq++)+'}]}';
    $.post(link, {
        "data" : data
    });
},
    
process : function (retdata) {
    if (!retdata.message) return;
    var lastMessage = null;
    for (var i = 0; i < retdata.message.data.messages.length; i++) {
        message = retdata.message.data.messages[i];
        if (message.seq) {
            talker.ack = message.seq + 1;
        }
        if (message.data) {
            if (message.data.type == "blist") {
                if (message.data.name == "buddy_removed") {
                    talker.removedBuddy(message.data.edata.buid);
                } else if (message.data.name == "buddy_request") {
                    talker.confirmAdd(message.data.edata);
                } else if (message.data.name == "buddy_icon"){
                    //TODO: display icon
                    //alert(message.data.icon);
                } else {
                    talker.contacts(message.data.edata);
                }
            }
            if(message.data.type == "conv") {
                if (message.data.name == "recv_unread_msgs") {
                    talker.unread(message.data.edata);
                } else {
                    if (talker.conversation(message.data.edata)) {
                        lastMessage = message.data.edata;
                    }
                }
            }
            if(message.data.type == "call") {
                var local = message;
                if(local.data.name == "streams_info") {
                    if (local.data.edata.is_initiator) {
                        talker.answer(local.data.edata.send_stream, local.data.edata.recv_stream);
                    } else {
                        $( '<div id="dialog-confirm" title="Incoming call">'+local.data.edata.buid+' is calling</div>' ).dialog({
                            resizable: false,
                            height:140,
                            modal: true,
                            buttons: {
                                "Answer": function() {
                                    $( this ).dialog( "close" );
                                    talker.answer(local.data.edata.send_stream, local.data.edata.recv_stream);
                                },
                                "Hang up": function() {
                                    $( this ).dialog( "close" );
                                    talker.refuse();
                                }
                            }
                        });
                    }
                } else if (local.data.name == "ended") {
                    talker.callEnded(local.data.edata.buid);
                }
            }
        }
    }
    if (lastMessage) {
        talker.markRead(lastMessage);
    }
},
    
processMessage : function (a) {
    text = $("#"+a+"-msg").val();
    if (text=="") {
        return false;
    }
    
    time = talker.getTime();
    message = time+" Me: "+text;
    if (!celebriotalkerchats[a]) {
        celebriotalkerchats[a] = [];
    }
    celebriotalkerchats[a].push(message);
    $("<div>"+message+"</div>").appendTo($("#"+a+"-messages"));
    $("#"+a+"-msg").val("");
    data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"buid":"'+a+'","msg":"'+text+'","uid":"'+uid+'","proto":"prpl-skype","ssid":"'+talker.ssid+'"},"method":"send_im"},"seq":'+(talker.seq++)+'}]}';
    $.post(link, {
        "data" : data
    });
    return false;
},
    
call : function (a) {
    data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"av"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"uid":"'+uid+'","proto":"prpl-skype","buid":"'+a+'","chat_type":"audio_chat","ssid":"'+talker.ssid+'"},"method":"start_chat"},"seq":'+(talker.seq++)+'}]}';
    $.post(link, {
        "data" : data
    });
    return false;
},
    
answer : function (send, recv) {
    $('<div id="celebriocaller"></div>').html(
        '<object id="flash_widget_call" width="400" height="208" type="application/x-shockwave-flash" data="https://imo.im/images/nchat.swf?6c448e9ab003739e8dd49fdc8f1b21db914fb957" style="visibility: visible; width: 400px; height: 208px;">'+
        '<param name="allowscriptaccess" value="always">'+
        '<param name="wmode" value="opaque">'+
        '<param name="flashvars" value="type=skype&connect_on_start=true&send_stream='+send+
        '&recv_stream='+recv+'&host=video0.imo.im&debug=conv net&audio_only=true&id=skype#'+send+
        '&buddy_icon=https://imo.im/assets/main/icn_default.png">'+
        //&setCookie=IMO.AVConv.flash_set_cookie&getCookie=IMO.AVConv.flash_get_cookie&removeCookie=IMO.AVConv.flash_rm_cookie&imo_callback_prefix=IMO.FlashWidget.callbacks.id_flash_widget_eumlzppj9taKRiAe.&log=console.log
        //"</object><a href='#' onclick='document.flash_widget_call.SetVariable(\"output\",{ av: 0});return false;'>Mute</a>").dialog();
        "</object>").dialog();
            
},
    
refuse : function (name, send) {
    data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"av"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"remote_ci":{"type":"skype","uid":"'+uid+'","proto":"prpl-skype","buid":"'+name+'"},"conv_id":"skype#'+send+'","msg":{"text":"Your buddy did not answer the call","message":{"type":"terminate_call","reason":"rejected"}},"ssid":"'+talker.ssid+'"},"method":"send_message"},"seq":'+(talker.seq++)+'}]}';
    $.post(link, {
        "data" : data
    });
    return false;
},
    
callEnded : function(name) {
    $("#dialog-confirm").remove();
    $("#celebriocaller").remove();
},
    
addBuddy : function (name) {
    data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"buid":"'+name+'","group":"Skype","uid":"'+uid+'","proto":"prpl-skype","ssid":"'+talker.ssid+'"},"method":"add_buddy"},"seq":'+(this.seq++)+'}]}';
    $.post(link, {
        "data" : data
    });
    return false;
},
    
removeBuddy : function (name) {
    data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[{"to":{"system":"im"},"from":{"system":"client","ssid":"'+talker.ssid+'"},"data":{"data":{"buid":"'+name+'","group":"Skype","uid":"'+uid+'","proto":"prpl-skype","ssid":"'+talker.ssid+'"},"method":"del_buddy"},"seq":'+(this.seq++)+'}]}';
    $.post(link, {
        "data" : data
    });
    return false;
},

removedBuddy : function (name) {
    $("#skype-"+name).parent().remove();
    $("#celebriotalkerapp_chatarea").html("Friend removed");
}
    
    
};
    
function createMessage(a) {
    $("#celebriotalkerapp_chatarea").html("<div class='celebriotalkerapp_messagebox'>\n\
                            <a href='#' onclick='talker.removeBuddy(\""+a+"\")'>Remove Friend</a>\n\
                            <div id='"+a+"-messages'></div>\n\
                            <textarea class='celebriotalkerapp_msg' id='"+a+"-msg'></textarea>\n\
                            <input type='button' id='celebriosend' value='Send' onclick='talker.processMessage(\""+a+"\")' />\n\
                            <input type='button' id='celebriocall' value='Call' onclick='talker.call(\""+a+"\")' />\n\
                            </div>");
    $("#celebriotalkerapp_header").html(a);
    var lastMessage;
    for (var number in celebriotalkerchats[$("#celebriotalkerapp_header").html()]) {
        message = celebriotalkerchats[$("#celebriotalkerapp_header").html()][number];
        //TODO: mark as read?? CHECK IT!!
        if (!message.timestamp) {
            $("#"+a+"-messages").append("<div class='talkermessage'>" +message+ "</div>");
        } else {
            time = talker.getTime(message.timestamp*1000);
            var msg = time+" "+ message.alias+": "+message.msg;
            $("#"+a+"-messages").append("<div class='talkermessage'>" +msg+ "</div>");
            lastMessage = message;
        }
    }
    talker.markRead(lastMessage);
}

function startPolling() {
    data = '{"ack":'+talker.ack+',"ssid":"'+talker.ssid+'","messages":[]}';
    $.post(link, {
        "data" : data
    }).complete( function() {
        startPolling();
    });
}

$(document).ready( function () {
    $.ajaxSetup({
        success : talker.process
    });
    talker.getSsid();
});



$(document).keydown( 
    function(event) {
        if (event.which == 13) {
            $("#celebriosend").trigger('click');
            event.preventDefault();
        }
    });